#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>

#include <tcpclient.h>
#include <log.h>

bool TcpClient::connect_to()
{
    struct sockaddr_in addr;

    ++conn_cnt;
    conn_ticks = get_ticks();

    if (ip.empty() || port <= 0) {
        log_print("TcpClient::connect_to: ip empty or port <= 0\n");
        return false;
    }

    if (fd >= 0 && conn_p)
        close_conn();

    if (fd < 0) {
        fd = socket(AF_INET, SOCK_STREAM, 0);

        if (fd < 0) {
            log_print("TcpClient::connect_to: socket failed: %s\n",
                      strerror(errno));
            return false;
        }
    }

    memset(&addr, 0, sizeof(struct sockaddr_in));

    addr.sin_family      = AF_INET;
    addr.sin_port        = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());

    if (connect(fd, (struct sockaddr *)&addr,
                sizeof(struct sockaddr_in)) < 0) {
        log_print("TcpClient::connect_to: connect failed: %s\n",
                  strerror(errno));
        return false;
    }

    conn_p = true;

    return true;
}

void TcpClient::close_conn()
{
    if (fd >= 0) {
        close(fd);
        fd = -1;
    }

    conn_p = false;
}
